package com.example.common.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import com.example.common.dto.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ControllerAdvice(basePackages = {"com.example.business.demo", "com.example.business.user", "com.example.common"})
public class CommonGlobalExceptionHandler extends BaseExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(CommonGlobalExceptionHandler.class);
    
    @ExceptionHandler(Exception.class)
    public ResponseEntity<BaseResponse<Void>> handleException(Exception e) {
        return handleException(e, ErrorCode.SYSTEM_ERROR, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(BizException.class)
    public ResponseEntity<BaseResponse<Void>> handleBizException(BizException e) {
        return handleException(e, ErrorCode.fromCode(e.getErrorCode()), e.getHttpStatus());
    }

    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<BaseResponse<Void>> handleNullPointerException(NullPointerException e) {
        return handleException(e, ErrorCode.NULL_POINTER_ERROR, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<BaseResponse<Void>> handleIllegalArgumentException(IllegalArgumentException e) {
        return handleException(e, ErrorCode.INVALID_PARAMETER, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<BaseResponse<Void>> handleValidationException(MethodArgumentNotValidException e) {
        return handleException(e, ErrorCode.VALIDATION_ERROR, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<BaseResponse<Void>> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        return handleException(e, ErrorCode.REQUEST_FORMAT_ERROR, HttpStatus.BAD_REQUEST);
    }
}